# coding:utf-8
from django.shortcuts import render
from blog.models import Article, Column


def index(request,id):
    # 获得文章分类
    columns = Column.objects.all()
    # 获得当前文章
    article = Article.objects.get(pk=id)
    reId = int(id)
    nextId = int(id)

    # 获得上一篇文章id
    while True:
        reId = reId - 1

        if reId <= 0:
            reArticleObj={'id':-1,'obj':None}
            break

        try:
            reArticle = Article.objects.get(pk=reId)
        except Article.DoesNotExist:
            continue
        else:
            reArticleObj={'id':reId,'obj':reArticle}
            break

    # 获得下一篇文章
    while True:
        nextId = nextId + 1

        if nextId > Article.objects.last().id:
            nexeArticleObj = {'id':-1,'obj':None}
            break

        try:
            nextArticle = Article.objects.get(pk=nextId)
        except Article.DoesNotExist:
            continue
        else:
            nexeArticleObj = {'id':nextId,'obj':nextArticle}
            break

    # 获得最后3篇文章
    # 获得最后一篇文章数
    lastNum = Article.objects.count()
    if lastNum - 15 < 0:
        startNum = 0
    else:
        startNum = lastNum - 15
    lastArticles = Article.objects.all()[startNum:lastNum]

    return render(request,'blog/Article/index.html',{'columns':columns,'article':article,'reArticle':reArticleObj,'nextArticle':nexeArticleObj,'lastArticles':lastArticles})

